package com.yzd.learnjava.typeinfo.pets;

import java.util.HashMap;
import java.util.Map;

public class TypeCounter extends HashMap<Class<?>, Integer>{
	private Class<?> baseType;
	public TypeCounter(Class<?> type) {
		this.baseType = type;
	}
	
	public void count(Object obj) {
		Class<?> type = obj.getClass();
		if(!baseType.isAssignableFrom(type)) {
			throw new RuntimeException("incorrect type");
		}
		countClass(type);
		
	}
	
	private void countClass(Class<?> type) {
		Integer qty = get(type);
		put(type, qty == null? 1 : qty + 1);
		Class<?> superClass = type.getSuperclass();
		if(superClass != null && baseType.isAssignableFrom(superClass)) {
			countClass(superClass);
		}
	}
	
	public String toString() {
		StringBuilder sb = new StringBuilder("{");
		for(Map.Entry<Class<?>, Integer> pair : entrySet()) {
			sb.append(pair.getKey().getSimpleName());
			sb.append("=");
			sb.append(pair.getValue());
			sb.append(", ");
		}
		sb.delete(sb.length() - 2, sb.length());
		sb.append("}");
		
		return sb.toString();
	}
}
